const mysql = require('mysql2/promise');
const bcrypt = require('bcryptjs');

const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 3306,
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || 'newhand',
  database: process.env.DB_NAME || 'hunaction',
  charset: 'utf8mb4',
  timezone: '+08:00'
};

async function createBasicData() {
  let connection;
  
  try {
    console.log('连接数据库...');
    connection = await mysql.createConnection(dbConfig);
    console.log('数据库连接成功');

    // 1. 创建管理员
    console.log('创建管理员账户...');
    const hashedPassword = await bcrypt.hash('admin123', 10);
    
    const [existingAdmin] = await connection.execute(
      'SELECT id FROM admins WHERE username = ?', 
      ['admin']
    );
    
    if (existingAdmin.length === 0) {
      await connection.execute(`
        INSERT INTO admins (username, password, real_name, role, is_active, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, NOW(), NOW())
      `, ['admin', hashedPassword, '系统管理员', 'super_admin', 1]);
      console.log('✓ 管理员账户创建成功');
    } else {
      console.log('✓ 管理员账户已存在');
    }

    // 2. 创建基本线索数据
    console.log('创建测试线索...');
    const testClues = [
      {
        clue_no: 'CL202506180001',
        title: '测试线索1 - 经济诈骗案',
        content: '这是一个测试线索的详细描述，涉及经济诈骗活动。内容长度超过20个字符以满足验证要求。',
        category: '经济犯罪',
        status: 'pending',
        priority: 2
      },
      {
        clue_no: 'CL202506180002',
        title: '测试线索2 - 涉恶团伙案',
        content: '发现涉恶团伙活动线索，需要进一步调查核实。该团伙涉嫌多项违法犯罪活动。',
        category: '涉黑涉恶',
        status: 'processing',
        priority: 3
      },
      {
        clue_no: 'CL202506180003',
        title: '测试线索3 - 毒品交易案',
        content: '发现可疑毒品交易活动，地点在城郊某废弃厂房。交易时间通常在深夜进行。',
        category: '毒品犯罪',
        status: 'completed',
        priority: 3
      }
    ];

    for (const clue of testClues) {
      const [existing] = await connection.execute(
        'SELECT id FROM clues WHERE clue_no = ?',
        [clue.clue_no]
      );
      
      if (existing.length === 0) {
        const [result] = await connection.execute(`
          INSERT INTO clues (
            clue_no, title, content, category, status, priority, 
            suspect_info, incident_time, incident_location, 
            view_count, created_at, updated_at
          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
        `, [
          clue.clue_no,
          clue.title,
          clue.content,
          clue.category,
          clue.status,
          clue.priority,
          '测试涉案人员信息',
          '2025-06-18 10:00:00',
          '测试地点',
          0
        ]);
        
        console.log(`✓ 线索 "${clue.title}" 创建成功，ID: ${result.insertId}`);
        
        // 创建处理历史记录
        const [adminResult] = await connection.execute('SELECT id, real_name FROM admins WHERE username = ?', ['admin']);
        if (adminResult.length > 0) {
          await connection.execute(`
            INSERT INTO clue_processing_logs (
              clue_id, admin_id, admin_name, action_type, old_value, new_value,
              processing_opinion, ip_address, user_agent, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
          `, [
            result.insertId,
            adminResult[0].id,
            adminResult[0].real_name,
            'status_change',
            'pending',
            clue.status,
            `线索已${clue.status === 'pending' ? '提交' : clue.status === 'processing' ? '开始处理' : '处理完成'}`,
            '127.0.0.1',
            'Test Script'
          ]);
          console.log(`  ✓ 处理历史记录创建成功`);
        }
      } else {
        console.log(`✓ 线索 "${clue.title}" 已存在`);
      }
    }

    console.log('✅ 基本测试数据创建完成！');
    console.log('');
    console.log('管理员账户信息：');
    console.log('用户名: admin');
    console.log('密码: admin123');
    console.log('');
    console.log('可以使用以下URL进行测试：');
    console.log('- 简单测试页面: http://localhost:3001/admin/simple-test.html');
    console.log('- 完整管理页面: http://localhost:3001/admin/clues.html');
    console.log('- 调试页面: http://localhost:3001/admin/debug.html');

  } catch (error) {
    console.error('创建数据失败:', error);
  } finally {
    if (connection) {
      await connection.end();
    }
    process.exit(0);
  }
}

createBasicData(); 